const User = require('@/models/sys/UserModel')
interface IUser {
  username: string,
  password: string
}
class UserService{
  async getList () {
    return await User.find()
  }
  async getById(ctx:any) {
    const {fields} = ctx.query
    const str = fields.split(';').join(' +')
    const user = await User.findById(ctx.params.id).select(' +' + str)
    if (!user) { ctx.throw(404, '用户不存在') }
    return user
  }
  
  async save(ctx:any) {
    const {name} = ctx.request.body
    const user = await User.findOne({name})
    if (user) {
      ctx.throw(409, '用户已存在！');
    }
    return await new User(ctx.request.body).save()
  }
  
  async update(ctx:any) {
    const user = await User.findOneAndUpdate(ctx.request.body.id, ctx.request.body)
    if (!user) {
      ctx.throw(404)
    }
    return {}
  }
  
  async remove(ctx:any) {
    const user = await User.findOneAndRemove(ctx.params.id)
    if (!user) {
      ctx.throw(404)
    }
    return user
  }
  
  async getFollowing(ctx:any) {
    const user = await User.findById(ctx.params.id).select('+following').populate('following')
    if (!user) {
      ctx.throw(404)
    }
    return user.following
  }
  
  async checkUserExist(ctx:any) {
    const user = await User.findById(ctx.params.id)
    return user
  }
  
  async follow(ctx:any) {
    const me = await User.findById(ctx.state.user._id).select('+following')
    if (!me.following.map((id:string) => id.toString()).includes(ctx.params.id)) {
      me.following.push(ctx.params.id)
      me.save()
    }
    return {}
  }
  
  async unfollow(ctx:any) {
    const me = await User.findById(ctx.state.user._id).select('+following')
    const index = me.following.map((id:string) => id.toString()).indexOf(ctx.params.id)
    if (index > -1) {
      me.following.splice(index, 1)
      me.save()
    }
    return {}
  }
  
  async getFollower(ctx:any) {
    const users = await User.find({following: ctx.params.id})
    return users
  }
}
module.exports = new UserService()